(function () {

    "use strict";

    sm.controller('wx-center-account-mobile-controller', ['$scope', '$http', 'Modal', 'Toast', function ($scope, $http, Modal, Toast){

        var api = {
            getSmsUrl: "/api/account/sms",
            bindUrl: '/api/account/doBind'
        };

        $scope.data = {
            mobile: "",
            code: ""
        };

        $scope.defaultCounts = 90;
        $scope.isCounting = false;
        $scope.sendCodeTxt = '获取验证码';
        $scope.receiveCode = false;

        $scope.getSms = function () {

            var regExp = new RegExp(/^1[34578]\d{9}$/);

            if (!$scope.data.mobile || !regExp.test($scope.data.mobile)) {
                Modal.alert({
                    title: "操作提示",
                    content: "手机号格式填写错误"
                });
                return false;
            }

            $http.get(api.getSmsUrl, {
                params: {
                    type: "bind",
                    mobile: $scope.data.mobile
                }
            }).success(function (res) {
                if (res.state) {
                    doCounts();
                    $scope.isCounting = true;
                    $scope.receiveCode = true;
                } else {
                    var err = res.error || '验证码获取失败';
                    Toast.error({title: err})
                }
            });
        };

        $scope.bindMobile = function () {
            if (!$scope.data.code) {
                Toast.error({title: "未填写验证码"});
                return false;
            }

            if (!$scope.receiveCode) {
                Modal.alert({title: "操作提示", 'content': "请获取验证码"});
                return false;
            }

            var reg = new RegExp(/^\d{4}$/);
            if (!reg.test($scope.data.code)) {
                Toast.error({title: "验证码错误"});
                return false;
            }

            $http.post(api.bindUrl, {
                mobile: $scope.data.mobile,
                type: 'bind',
                code: $scope.data.code
            }).success(function (res) {
                if (res.state) {
                    window.location = '/center';
                } else {
                    Toast.error({title: "绑定失败"});
                }
            });
        };

        function doCounts() {
            var timer = setInterval(function () {
                $scope.defaultCounts -= 1;
                if ($scope.defaultCounts <= 1) {
                    $scope.isCounting = false;
                    $scope.sendCodeTxt = '获取验证码';
                    clearInterval(timer);
                } else {
                    $scope.sendCodeTxt = '等待（'+$scope.defaultCounts+'）秒';
                }
                $scope.$apply();
            }, 1000)
        }

    }]);
})();

